var apiUrl = 'http://streetshop.com/api/v1'; //放入后台接口的url
const apiMock = require('./api-mock.js'); // 导入API模拟器

var baseUrl = '';

baseUrl = apiUrl

// 开发模式下使用模拟数据
const USE_MOCK_DATA = true; // 正式环境请设置为false

// 处理模拟API请求
const handleMockRequest = (url, method, data) => {
	console.log('Mock API Request:', url, method, data);
	
	// 定义需要模拟的API接口
	const mockApiMap = {
		'zhanke/user/login': apiMock.mockLogin,
		'zhanke/user/check_password_status': apiMock.mockCheckPasswordStatus,
		'zhanke/user/change_password': apiMock.mockChangePassword,
		'zhanke/user_info': apiMock.mockUserInfo,
		'zhanke/logout': apiMock.mockLogout
	};
	
	// 检查是否需要模拟
	if (mockApiMap[url]) {
		return mockApiMap[url](data).then(mockData => {
			console.log('Mock API Response:', mockData);
			return {
				statusCode: 200,
				data: mockData
			};
		}).catch(error => {
			console.error('Mock API Error:', error);
			return {
				statusCode: 500,
				data: {
					code: 500,
					msg: '模拟API错误',
					data: null
				}
			};
		});
	}
	
	// 不需要模拟，返回null继续正常请求
	return null;
}


// 请求成功后操作
const successToast = (res = {}, url = '', isJumpFail = true) => {
	if (res.statusCode != 401 || res.statusCode != 403) {
		if (res.data.code == 200) {
			console.log('延迟successtoast.........', res);
			if (res.data.msg == 'success') {
				title = '操作成功！';
			} else {
				title = res.data.msg;
			}
			uni.showToast({
				icon: "success",
				title: title,
				mask: true,
				duration: 2000,
				success() {
					if (url && isJumpFail) {
						setTimeout(() => {
							uni.reLaunch({
								url: url
							});
						}, 2000)
					}
				}
			});
		}
	}
}

const errorToast = (res = {}, url = '', isJumpFail = false) => {
	if (res.statusCode != 401 || res.statusCode != 403) {
		if (res.data.code >= 10000) {
			console.log('延迟errortoast.........', res);
			uni.showModal({
				title: '错误提示',
				content: res.data.msg,
				showCancel: false,
				success() {
					if (url && isJumpFail) {
						setTimeout(() => {
							uni.reLaunch({
								url: url
							});
						}, 2000)
					}
				}
			});
		}
	}
}

//封装request请求
const sendRequest = (url, method = 'GET', data = {}, contentType) => {
	// 检查是否使用模拟数据
	if (USE_MOCK_DATA) {
		const mockResponse = handleMockRequest(url, method, data);
		if (mockResponse) {
			return mockResponse;
		}
	}
	
	//判断header提交数据类型
	let types = '';
	if (method == 'POST' && !contentType) {
		types = 'application/x-www-form-urlencoded'
	} else if (method == 'POST' && contentType) {
		types = contentType
	} else {
		types = 'application/json';
	}


	var bases = baseUrl + '/' + url;

	var token = uni.getStorageSync('token') || '';
	var hasToken = false;
	if (token) {
		hasToken = true;
	}
	return new Promise(function(resolve, reject) {
		uni.request({
			url: bases,
			data: data,
			method: method,
			header: {
				'Content-Type': types,
				'Accept': 'application/json, text/javascript, */*; q=0.01',
				'Authorization': token
			},
			success(res) {
				// console.log('-----------', url, data, res);
				if (res.header && res.header.authorization) {
					uni.setStorageSync('token', res.header.authorization);
					resolve(res);
				} else {
					var code = res.statusCode;
					const currentType = data.type || 'zhanke'; // 保存当前的data.type，默认为zhanke
					
					if (code === 401 || code === 403) {
						// 登录过期-移除token,重新登录 
						uni.removeStorageSync('token');
						module.exports.hasToken = false;
						uni.hideLoading(); // 确保关闭加载框
						
						uni.showModal({
							title: '登录提示',
							content: '身份已过期，请重新登录后再来操作！',
							showCancel: false,
							success: function(ress) {
								if (ress.confirm) {
									// if (currentType === 'sales') {
									// 	uni.reLaunch({
									// 		url: '/pages/index/index_sales'
									// 	});
									// } else if (currentType === '战客') {
										uni.reLaunch({
											url: '/pages/login/login'
										});
									// } else {
									// 	uni.reLaunch({
									// 		url: '/pages/index/index'
									// 	});
									// }
								}
							}
						});
					} else {
						errorToast(res);
						resolve(res);
					}
				}
			},
			fail(err) {
				console.log('fail-----------', url, data, err);
				uni.hideLoading(); // 确保隐藏加载框
				reject(err);
			},
			complete() {
				// 请求完成后的处理
			}
		})
	})
}
var token = uni.getStorageSync('token') || '';
var hasToken = false;
if (token) {
	hasToken = true;
}

module.exports = {
	'apiUrl': apiUrl,
	'sendRequest': sendRequest,
	'hasToken': hasToken,
	'successToast': successToast,
	'errorToast': errorToast
}